# -*- coding: utf-8 -*-

import re
import os
import chardet

#检测指定文件的编码格式。
def get_file_encoding(file_path):
    """
    检测指定文件的编码格式。
    
    参数:
        file_path (str): 文件路径
    
    返回:
        str: 检测到的编码格式（如 utf-8, gbk 等）
    """
    with open(file_path, 'rb') as f:
        raw_data = f.read(10000)  # 读取前10KB用于检测
    result = chardet.detect(raw_data)
    return result['encoding']
#读取指定目录下的所有文件，并执行指定处理函数。
def read_files_with_extension(directory, extensions, file_handler, file_handler_data = None):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if any(file.endswith(ext) for ext in extensions):
                file_path = os.path.join(root, file)
                file_handler(file_path, file_handler_data)

#替换文件内容                
def replace_in_file(file_path, replace_handler):
    try:
        encoding = get_file_encoding(file_path)
        # print(f"检测文件编码: {file_path} -> 编码: {encoding}")
        
        with open(file_path, 'r', encoding=encoding, errors='ignore') as f:
            content = f.read()
            # print(f"文件内容:\n{content}\n{'-'*80}")
            newcontent = replace_handler(content)
            if newcontent != content:
                print(f"文件 {file_path} 替换成功 字节差异:{len(newcontent) - len(content)}")
                with open(file_path, 'w', encoding=encoding) as f_out:
                    f_out.write(newcontent)
            # else:
            #     print(f"文件 {file_path} 没有需要替换的内容")
    except Exception as e:
        print(f"检测文件编码: {file_path} -> 编码: {encoding}")
        print(f"无法处理文件 {file_path}: {e}")
def read_key_value_conf(file_path):
    """
    读取文件中的 key=value 内容并保存到字典中。
    """
    key_value_map = {}
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            line = line.strip()
            if line and '=' in line:
                key, value = line.split('=', 1)
                key_value_map[key] = value
    return key_value_map

if __name__ == "__main__":
    pass